package com.dt.dubai.core.qrcode.WXcode;

import net.sf.json.JSONObject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 *   微信专利版权，太阳码
 */

@RestController
@RequestMapping("WX")
public class WX {

    //获取token的接口地址
    public final static String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";

    /**
     * 获取access_token
     *
     * @param appid
     * @param appsecret
     * @return
     */
    public String getAccess_token(String appid, String appsecret) {
        try {
            String requestUrl = access_token_url.replace("APPID", appid).replace("APPSECRET", appsecret);
            JSONObject jsonObject = httpsRequest(requestUrl, "GET", null);
            return jsonObject.getString("access_token");
        } catch (Exception e) {
            return "errer";
        }
    }

    /**
     *
     * @Title: httpsRequest
     * @Description: 发送请求,返回JSONObject对象
     * @param requestUrl
     * @param requestMethod
     * @param outputStr
     * @return
     * @throws Exception
     */
    public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) throws Exception {
        JSONObject jsonObject = null;
        try {
            // 建立连接
            URL url = new URL(requestUrl);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 设置请求方式
            conn.setRequestMethod(requestMethod);
            // 当outputStr不为null时,向输出流写数据
            if (null != outputStr) {
                OutputStream outputStream = conn.getOutputStream();
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }
            // 获取输入流
            InputStream inputStream = conn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            // 读取响应内容
            StringBuffer buffer = new StringBuffer();
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            // 关闭资源
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            conn.disconnect();
            jsonObject = JSONObject.fromObject(buffer.toString());
        } catch (Exception e) {
            throw new Exception("请求/解析失败");
        }
        return jsonObject;
    }

    @GetMapping("/createImgByCompanyId")
    @ResponseBody
    // 依据公司信息生成个性化小程序码,返回小程序码名称
    public String createImgByCompanyId(String companyId,String dir) {
        // 获取token
        String appid = "wxc699b65a8492a88e";
        String appsecret = "d773577000a6f3eca6cc36c7776f3477";
        String token = getAccess_token(appid, appsecret);
        // 生成小程序码接口url
        String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=ACCESS_TOKEN".replace("ACCESS_TOKEN", token);
        // 二维码中信息
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("path", "pages/index/index");// 你二维码中跳向的页面
        map.put("scene", companyId);// 携带参数
        JSONObject json = JSONObject.fromObject(map);
        String js = json.toString();
        // 生成二维码
        try {
            CreateImgUtil.httpPostWithJSON(url, js, companyId,dir);
            return companyId;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

}
